<?php
/**
*	@author SignpostMarv Martin
*	@package LLSD
*/

/**
*	The class used to represent binary LLSD nodes- allows a native PHP data type to hold binary elements in order to differentiate them from normal strings
*	@package LLSD
*/
class uhu_LLSD_binary extends uhu_LLSD_common
{
/**
*	@var string The contents of the binary element.
*/
	protected $data;
/**
*	@var string The encoding type specified in the binary node
*/
	protected $encoding;
/**
*	@var bool Whether to throw an exception if an unsupported encoding is found.
*/
	protected static $fail_on_unsupported_encoding = true;

/**
*	Builds an instance of uhu_LLSD_binary.
*	@param SimpleXMLElement The binary node
*	@uses uhu_LLSD_binary::$data
*/
	public function __construct(SimpleXMLElement $data)
	{
		$this->encoding = current(current($data->attributes()));
		if($this->encoding !== 'base64' && self::$fail_on_unsupported_encoding === true)
		{
			throw new uhu_LLSD_exception('Unsupported binary encoding found.',104);
		}
		$this->data = (string)$data;
	}
/**
*	Use to toggle whether exceptions should be thrown if an unsupported encoding is found.
*	@param bool Set to false if binary elements aren't going to be decoded.
*	@return void	
*/
	public static function fail_on_unsupported_encoding($flag=true)
	{
		self::$fail_on_unsupported_encoding = (bool)$flag;
	}
/**
*	@return string The encoding of the binary element.
*	@uses uhu_LLSD_binary::$encoding
*/
	public function encoding()
	{
		return $this->encoding;
	}
/**
*	@return string The binary data
*	@uses uhu_LLSD_binary::$data
*/
	public function __toString()
	{
		return $this->data;
	}
/**
*	Rather pointless, given that only base64 is supported currently.
*	@param string The data to be encoded.
*	@return string base64-encoded version of the data supplied.
*/
	public static function encode($data)
	{
		return base64_encode($data);
	}
/**
*	Decodes the binary data.
*	@return string the decoded data.
*	@uses uhu_LLSD_binary::encoding()
*	@uses uhu_LLSD_exception
*/
	public static function decode(uhu_LLSD_binary $data)
	{
		if($data->encoding() !== 'base64')
		{
			throw new uhu_LLSD_exception('Unsupported binary encoding found.',104);
		}
		return base64_decode((string)$data);
	}
}
?>